#ifndef _JOYSTICK_H_
#define _JOYSTICK_H_

#include <RCSwitch.h>

RCSwitch receiver;              // RF433 接收器
uint32_t received_value = 0;    // RF433 接收到的数据

inline void process_rf433 ();
inline void joystick_action (uint32_t);

inline void joystick_action (uint32_t value) {
    // joystick command
    value &= 0x3ffff;
/*
    Serial.print ("     joystick send to me: ");
    Serial.println (value, HEX);    
*/
    uint8_t y = value & 0xff;
    uint8_t x = (value >> 8) & 0xff;
    uint8_t en_y = (value >> 16) & 1;
    uint8_t en_x = (value >> 17) & 1;
/*
    Serial.print ("en_x = "); Serial.print (en_x);
    Serial.print (", en_y = "); Serial.print (en_y);
    Serial.print (", x = "); Serial.print (x);
    Serial.print (", y = "); Serial.println (y);
*/
    if (abs (x) <= 64) {
        y = map (y, 0, 255, 64, 255);
/*
        Serial.print ("mapped y = ");
        Serial.println (y);
*/
        if (y <= 64) {
            pause ();
        } else {
            if (en_y == 0) {
//                Serial.println ("forwarding ...");
                pwm_forward (y);
            } else {
//                Serial.println ("backwarding ...");
                pwm_backward (y);
            }
        }
    } else if (abs (x) > 64 && abs (x) <= 200) {
        if (en_x == 0) {
//            Serial.println ("pwm left");
            pwm_left (x);
        } else {
//            Serial.println ("pwm right");
            pwm_right (x);
        }
    } else {
        if (en_x == 0) {
//            Serial.println ("turn left");
            left ();
        } else {
//            Serial.println ("trun right");
            right ();
        }
    }
}

inline void process_rf433 () {
    if (receiver.available()) {
        unsigned long value = receiver.getReceivedValue();
        if (received_value != value) {
            received_value = value;
            if ((value & 0x700000) == 0) {
                joystick_action (value);                
            } else {
                // button command
                value >>= 20;
            }
        }
        receiver.resetAvailable();
    }
}
#endif // _JOYSTICK_H_
